<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button
            v-allow="'import_employee'"
            type="warning"
            size="small"
            @click="$router.push('/employees/import')"
          >导入excel</el-button>
          <el-button
            type="danger"
            size="small"
            @click="hExportExcel"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <!-- 具体页面结构 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{ prop: 'workNumber' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>

          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder
                :src="scope.row.staffPhoto"
              /></template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="账户状态" prop="" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(scope.row)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页组件 -->
          <el-pagination
            background
            :current-page="pageParams.page"
            :page-sizes="[10, 20]"
            :page-size="pageParams.size"
            :total="total"
            layout="total, sizes, prev,pager,next, jumper"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
          <el-pagination layout="prev, pager, next" />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      v-if="showDialog"
      title="新增员工"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :visible.sync="showDialog"
    >
      <addor-edit @success="hSuccess" @close="showDialog = false" />
    </el-dialog>
    <!-- 使用组件 -->
    <el-dialog
      title="分配角色权限"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <!-- v-if="showDialogRole" -->
      <assign-role
        ref="assignRole"
        :employee-id="curEmployeId"
        @close="showDialogRole = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
// 导入枚举信息
import EmployeeEnum from '@/constant/employees'

import addorEdit from './empDialog'

// 引入组件
import AssignRole from './assignRole'

// Array.reduce(function(累加器,当前值,下标){}, 初始值)
const obj = EmployeeEnum.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})

console.log('枚举信息', EmployeeEnum.hireType, obj)

export default {
  components: {
    'addor-edit': addorEdit,
    AssignRole // 注册组件
  },
  data() {
    return {
      list: [],
      pageParams: { page: 1, size: 10 },
      total: 0,
      showDialog: false,
      showDialogRole: false, // 是否显示分配角色弹框
      curEmployeId: '' // 当前的员工编号
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    hSuccess() {
      this.showDialog = false

      // 添加成功，进入最后一页看数据
      this.total++

      // 最后一页
      this.pageParams.page = Math.ceil(this.total / this.pageParams.size)

      this.loadEmployeeList()
    },
    hClose() {
      this.showDialog = false
    },
    // 删除
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log(res)
        // 1. 提示
        this.$message.success('删除成功')

        // 2. 如果当前表格中只有一条，删除之后自动请求上一页数据
        if (this.pageParams.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 3. 重新请求
        this.loadEmployeeList()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch(err => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams)
        console.log('员工信息是', res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    format(typeNum) {
      // // 从hireType中 通过id找到对应的元素的value
      // const item = EmployeeEnum.hireType.find(it => it.id === num)
      // if (item) {
      //   return item.value
      // } else {
      //   return '不能确定'
      // }
      // return ? '正式' : '非正式'
      return obj[typeNum]
    },
    // 用户点击了页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    hSizeChange(curPageSize) {
      // 1. 更改每页的条数
      this.pageParams.size = curPageSize

      // 2. 重发请求
      this.loadEmployeeList()
    },
    formatDate(rows) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      console.log('做格式转换', rows)
      /** *
       * rows:
       * [
       *  {mobile:'13612345678', username:'管理员'.....}
       *  {mobile:'13612545678', username:'小王'.....}
       * ]
       *
       *
       *
       *  header:  [手机, 用户名]
       *  data: [ ['13612345678', '管理员'], ['13612545678', '小王'] ]
       */
      // 把英文的key转成中文的表头
      const enKeys = Object.keys(rows[0])

      const header = enKeys.map(enKey => map[enKey])

      const data = rows.map(obj => {
        return Object.values(obj)
      })
      console.log(enKeys, header, data)

      return {
        header,
        data // [ ['13612345678', '管理员'], [] ]
      }
    },
    // 导出
    async hExportExcel() {
      // 1. 求数据
      const res = await getEmployeeList(this.pageParams)
      console.log('员工信息是', res.data.rows)
      // 2. 做格式转换
      const { header, data } = this.formatDate(res.data.rows)
      console.log('结果', header, data)
      // 3. 调用Export2Excel保存数据到excel

      import('@/views/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '123', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 用户点击了分配角色
    hAssignRole({ id }) {
      console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curEmployeId = id
      console.log('父组件', this.curEmployeId)
      // this.$nextTick
      // 直接找到子组件，调用方法去获取最新的数据
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
        // console.log('子组件中的props', this.$refs.assignRole.employeeId)
      })
    }
  }
}
</script>
